const db = require('../db');

class MessageModel {
    // 创建新消息
    static async create(messageData) {
        try {
            const [result] = await db.query('INSERT INTO messages SET ?', messageData);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 获取两个用户之间的聊天记录
    static async getMessagesBetweenUsers(userId1, userId2, limit = 50) {
        try {
            const [result] = await db.query(
                `SELECT m.*, 
                 u1.name as sender_name, u1.avatar as sender_avatar,
                 u2.name as recipient_name, u2.avatar as recipient_avatar
                 FROM messages m
                 JOIN users u1 ON m.sender_id = u1.id
                 JOIN users u2 ON m.recipient_id = u2.id
                 WHERE (m.sender_id = ? AND m.recipient_id = ?)
                 OR (m.sender_id = ? AND m.recipient_id = ?)
                 ORDER BY m.timestamp DESC LIMIT ?`,
                [userId1, userId2, userId2, userId1, limit]
            );
            return result;
        } catch (error) {
            console.error('获取聊天记录失败:', error);
            throw error;
        }
    }

    // 将消息标记为已读
    static async markAsRead(senderId, recipientId) {
        try {
            const [result] = await db.query(
                'UPDATE messages SET is_read = 1 WHERE sender_id = ? AND recipient_id = ? AND is_read = 0',
                [senderId, recipientId]
            );
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 获取未读消息数量
    static async getUnreadCount(userId) {
        try {
            const [rows] = await db.query(
                'SELECT COUNT(*) as count FROM messages WHERE recipient_id = ? AND is_read = 0',
                [userId]
            );
            return rows[0].count;
        } catch (error) {
            throw error;
        }
    }

    // 删除聊天记录
    static async deleteMessages(senderId, recipientId, isRead = null) {
        try {
            let query = 'DELETE FROM messages WHERE (sender_id = ? AND recipient_id = ?)';
            const params = [senderId, recipientId];

            // 如果指定了isRead，则添加该条件
            if (isRead !== null) {
                query += ' AND is_read = ?';
                params.push(isRead);
            }

            const [result] = await db.query(query, params);
            return result;
        } catch (error) {
            throw error;
        }
    }
}

module.exports = MessageModel; 